package com.example.baiduapi.Scoket.websocket.handler;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.example.baiduapi.Alibaba.Chat.pojo.ChatResponse;
import com.example.baiduapi.Mapper.mysqlMapper.UserMapper;
import com.example.baiduapi.Scoket.utils.JsonUtil;
import com.example.baiduapi.Scoket.websocket.constant.ConstantPool;
import com.example.baiduapi.Scoket.websocket.service.ChatService;/*
import com.example.baiduapi.Scoket.websocket.service.RobotService;*/
import com.example.baiduapi.Util.*;
import com.example.baiduapi.pojo.Chatmessage;
import com.example.baiduapi.pojo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @Description: WebSocket处理器
* @Author: liujh
* @Date: 2021/12.25
*/
@Component
public class MyWebSocketHandler implements WebSocketHandler{

    // 防止ID超长的截取
    private int MAX_IDLEN = 10;
	private Logger logger = LoggerFactory.getLogger(MyWebSocketHandler.class);
	public static Map<String,WebSocketSession> userSessions  = new ConcurrentHashMap<String, WebSocketSession>();
    public static Map<String,WebSocketSession> webSocketSessions = new ConcurrentHashMap<String, WebSocketSession>();

    /*@Autowired
    RobotService robotService;*/
    @Autowired
    ChatService chatService;

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    UserMapper userMapper;

    /**
     * @Description: 用户连接上WebSocket的回调
     * @Param: [webSocketSession]
     * @return: void
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        logger.info("用户:{}webssh连接", String.valueOf(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY)));
        String userUUID = webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY).toString();
        userSessions.put(userUUID, webSocketSession);
    }

    /**
     * @Description: 收到消息的回调
     * @Param: [webSocketSession, webSocketMessage]
     * @return: void
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
    	// webSocketSession示例[id=cee1b08d-9910-057a-78bb-e43ae1d91ff8, uri=ws://localhost:8081/websocket]
        // webSocketMessage示例TextMessage payload=["{\"test\"..], byteCount=18, last=true]

    	//设置更新最后一后键盘或鼠标事件的到达时间
    	//robotService.setLastestActionTime(System.currentTimeMillis());
        if (webSocketMessage instanceof TextMessage) {

    		//logger.info("用户:{},发送命令:{}", webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY), webSocketMessage.toString());
    		Map<String,Object> playload = JsonUtil.castToObject(webSocketMessage.getPayload().toString());
            Object txt = playload.get("txt");
            Object username = playload.get("username");
            Object token = playload.get("token");
            Object getUser = playload.get("getUser");
            // 接收用户syste 判断是否已登
            if (getUser.equals("system")){
                UserInfo userInfoByID = userMapper.getUserInfoByID(username.toString());
                WebSocketSession receiverSession = userSessions.get(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY).toString()); // 根据UUID获取对应的WebSocketSession
                if (userInfoByID.getLoginNumber() != null && Integer.valueOf(userInfoByID.getLoginNumber()) < 2){
                    if (receiverSession != null && StringUtils.isNotBlank(txt.toString())) {
                        receiverSession.sendMessage(new TextMessage((username+"checkedLoginStateTrue")));
                    }
                } else {
                    userMapper.updateLoginState(username.toString(), "0");
                    if (receiverSession != null && StringUtils.isNotBlank(txt.toString())) {
                        receiverSession.sendMessage(new TextMessage((username+"checkedLoginStateFalse")));
                    }
                }
                return;
            }

            //回放处理客户端发送过来的键盘或鼠标事件,在服务端这边重新执行一遍
    	//	robotService.actionEvent(playload);
            String message = "";
            try {
                //gpt聊天
                System.out.println("发给机器人的内容："+txt.toString());
                ChatResponse chat = chatService.chat(txt.toString());
                Chatmessage chatmessage = new Chatmessage();
                chatmessage.setID(token.toString()+ DateUtil.nowDateTime()); // 消息ID
                chatmessage.setMessageID((token.toString()+ DateUtil.nowDateTime())); // 消息ID
                chatmessage.setCreateUser(username.toString()); // 创建消息ID
                chatmessage.setInitiCreateUser((token.toString()+ DateUtil.nowDateTime())); // 初始消息ID
                chatmessage.setMessage/*(txt.toString());*/(EncPassword.convertMD5(txt.toString().substring(0,txt.toString().length() >=MAX_IDLEN?MAX_IDLEN:txt.toString().length())));// 加密消息内容
                chatmessage.setGetUser(getUser.toString());// 接收消息用户
                chatService.addMessage(chatmessage);
                message = chat.getOutput().getText();
                System.out.println("机器人内容："+message);

                Chatmessage chatmessageRobot = new Chatmessage();
                // 消息ID为消息前0-3，防止ID超长
                chatmessageRobot.setID/*(("robot"+message.substring(0,txt.toString().length() >=MAX_IDLEN?MAX_IDLEN:txt.toString().length())+ DateUtil.nowDateTime()));*/ (("robot"+EncPassword.string2MD5(message.substring(0,txt.toString().length() >=MAX_IDLEN?MAX_IDLEN:txt.toString().length()))+ DateUtil.nowDateTime())); // 发送用户ID
                chatmessageRobot.setMessageID/*(("robot"+message+ DateUtil.nowDateTime()));*/ (("robot"+EncPassword.string2MD5(message.substring(0,txt.toString().length() >=MAX_IDLEN?MAX_IDLEN:txt.toString().length()))+ DateUtil.nowDateTime())); // robot+信息MD5码+时间
                chatmessageRobot.setCreateUser("robot"); // 创建消息ID
                chatmessageRobot.setInitiCreateUser/*(("robot"+message+ DateUtil.nowDateTime()));*/ (("robot"+EncPassword.string2MD5(message.substring(0,txt.toString().length() >=MAX_IDLEN?MAX_IDLEN:txt.toString().length()))+ DateUtil.nowDateTime())); // robot+信息MD5码+时间
                chatmessageRobot.setMessage/*(message); */(EncPassword.convertMD5(message));// 加密消息内容
                chatmessageRobot.setGetUser(username.toString());// 接收消息用户
                chatService.addMessage(chatmessageRobot);
                //把txt发送给前端

                if (webSocketMessage instanceof TextMessage) {
                    // 判断消息的接收者
                    WebSocketSession receiverSession = userSessions.get(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY).toString()); // 根据UUID获取对应的WebSocketSession
                    // 发送消息给接收者
                    if (receiverSession != null && StringUtils.isNotBlank(message)) {
                        receiverSession.sendMessage(new TextMessage(message));
                    }
                }
            } catch (IOException e) {
                logger.error("发送消息失败,异常为：{}，我的消息为：{}，回复的消息为，{}", e,txt,message);
                throw new RuntimeException(e);
            }
        } else if (webSocketMessage instanceof BinaryMessage) {



        } else if (webSocketMessage instanceof PongMessage) {

        } else {
            logger.error("Unexpected WebSocket message type: " + webSocketMessage);
        }
    }

  /*  @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String txt = "ceshixiaoxi";
        if (webSocketMessage instanceof TextMessage) {
            // 判断消息的接收者
            WebSocketSession receiverSession = userSessions.get(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY).toString()); // 根据UUID获取对应的WebSocketSession

            // 发送消息给接收者
            if (receiverSession != null && StringUtils.isNotBlank(txt)) {
                receiverSession.sendMessage(new TextMessage(txt));
            }
        }
    }*/

    /**
     * @Description: 出现错误的回调
     * @Param: [webSocketSession, throwable]
     * @return: void
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        logger.error("数据传输错误");
    }

    /*96
     * @Description: 连接关闭的回调
     * @Param: [webSocketSession, closeStatus]
     * @return: void
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        logger.info("用户:{}断开webssh连接", String.valueOf(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY)));

        userSessions.remove(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY).toString());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }


    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Hello, World!");
        if (SystemTray.isSupported()) {

// 创建一个系统托盘图标

            SystemTray tray = SystemTray.getSystemTray();
            Image image = Toolkit.getDefaultToolkit().getImage("/C:/Users/Administrator/Pictures/45966123_fb2facfb7fb48d5d6b876efbed3e3dcc.jpg");

            TrayIcon trayIcon = new TrayIcon(image, "Message Notification");



// 添加弹出菜单

            PopupMenu popup = new PopupMenu();

            MenuItem item = new MenuItem("Show Message");

            item.addActionListener(e -> JOptionPane.showMessageDialog(null, "Hello, World!"));

            popup.add(item);

            trayIcon.setPopupMenu(popup);



// 添加到系统托盘

            try {

                tray.add(trayIcon);

            } catch (AWTException e) {

                e.printStackTrace();

            }

        }
    }

}
